<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form
        ref="dataForm"
        label-width="120px"
        label-position="right"
        :model="dataMap"
      >
        <el-col :span="8">
          <div>
            <el-form-item label="登录名:" prop="loginName">
              <label>{{ dataMap.loginName }}</label>
            </el-form-item>
            <el-form-item label="用户名:" prop="userName">
              <label>{{ dataMap.userName }}</label>
            </el-form-item>
            <el-form-item label="性别:" prop="sexKey">
              <label>{{ dataMap.sexKey == "Sex_1" ? "男" : "女" }}</label>
            </el-form-item>
            <el-form-item label="出生日期:" prop="birthday">
              <label>{{ dataMap.birthday }}</label>
            </el-form-item>
            <el-form-item label="身份证号:" prop="idNumber">
              <label>{{ dataMap.idNumber }}</label>
            </el-form-item>
            <el-form-item label="电话号码:" prop="phoneNumber">
              <label>{{ dataMap.phoneNumber }}</label>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div>
            <el-form-item label="登录总次数:" prop="loginNum">
              <label style="color: red">{{ dataMap.loginNum }}</label>
            </el-form-item>
            <el-form-item label="今日登录次数:" prop="loginNumToday">
              <label style="color: red">{{ dataMap.loginNumToday }}</label>
            </el-form-item>
            <el-form-item label="最后登录时间:" prop="lastTime">
              <label style="color: red">{{ dataMap.lastTime }}</label>
            </el-form-item>
            <el-form-item label="最后登录IP:" prop="lastIp">
              <label style="color: red">{{ dataMap.lastIp }}</label>
            </el-form-item>
            <el-form-item label="密码错误次数:" prop="errorCount">
              <label style="color: red">{{ dataMap.errorCount }}</label>
            </el-form-item>
          </div>
        </el-col>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="个人简介：" prop="introduction">
              <el-input
                type="textarea"
                v-model="dataMap.introduction"
                readonly
                autosize
                resize="none"
                id="textArea"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <div style="text-align: center">
              <el-button type="info" @click="handleEdit()">编辑信息</el-button>
              <el-button type="success" @click="handlePwd()"
                >修改密码</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-row>
    <!-- 弹出新增窗口 -->
    <el-dialog
      title="个人信息编辑"
      :visible.sync="dialogFormVisible"
      width="500px"
    >
      <el-form
        ref="pojoForm"
        :rules="rules"
        label-width="100px"
        label-position="right"
        :model="pojo"
        style="width: 400px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="pojo.userName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sexKey">
          <el-select
            v-model="pojo.sexKey"
            placeholder="请选择性别"
            style="width: 280px"
          >
            <el-option
              v-for="option in sexKeyOptions"
              :key="option.type"
              :label="option.name"
              :value="option.type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="pojo.birthday"
            type="date"
            placeholder="选择日期"
            style="width: 280px"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="身份证号:" prop="idNumber">
          <el-input v-model="pojo.idNumber"></el-input>
        </el-form-item>
        <el-form-item label="电话号码:" prop="phoneNumber">
          <el-input v-model="pojo.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="个人简介：" prop="introduction">
          <el-input
            type="textarea"
            v-model="pojo.introduction"
            rows="5"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateData('pojoForm')"
          >确 定</el-button
        >
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改密码弹窗 -->
    <el-dialog
      title="修改密码"
      :visible.sync="dialogFormPwdVisible"
      width="500px"
    >
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        style="width: 400px"
      >
        <el-form-item label="原密码" prop="oldPass">
          <el-input type="password" v-model="ruleForm.oldPass"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="$refs['ruleForm'].resetFields()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import store from "@/store/index";
import { getInfo, checkPwd, updatePwd } from "@/api/user";
import { update } from "@/api/omp/ompUser";
import Moment from "moment";
// 性别
const sexKeyOptions = [
  { type: "Sex_1", name: "男" },
  { type: "Sex_2", name: "女" },
];
export default {
  data() {
    // 检验原密码
    const validateOldPass = (rule, value, callback) => {
      checkPwd(store.state.user.userKey, value).then((response) => {
        const resp = response;
        if (resp.flag) {
          callback();
        } else {
          callback(new Error(resp.message));
        }
      });
    };
    //  检验确认密码是否一致
    const validatecheckPass = (rule, value, callback) => {
      if (value != this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      dataMap: {},
      pojo: {
        userKey: "",
        userName: "",
        sexKey: "",
        birthday: null,
        idNumber: "",
        phoneNumber: "",
        introduction: "",
      }, // 提交的数据
      ruleForm: {
        oldPass: "",
        pass: "",
        checkPass: "",
      },
      dialogFormVisible: false, // 控制对话框
      dialogFormPwdVisible: false,
      sexKeyOptions: sexKeyOptions, // 程序类型，ES6语法
      rules: {
        // 校验规则
        userName: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur",
          },
        ],
        sexKey: [
          {
            required: true,
            message: "性别不能为空",
            trigger: "blur",
          },
        ],
        birthday: [
          {
            required: true,
            message: "出生日期不能为空",
            trigger: "blur",
          },
        ],
        oldPass: [
          { required: true, message: "原密码不能为空", trigger: "blur" },
          { validator: validateOldPass, trigger: "blur" },
        ],
        pass: [{ required: true, message: "新密码不能为空", trigger: "blur" }],
        checkPass: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { validator: validatecheckPass, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.getInfo();
    },
    // 查询功能
    getInfo() {
      var token = store.state.user.token;
      getInfo(token).then((response) => {
        const resp = response;
        if (resp.flag) {
          this.dataMap = resp.data;
          // 生日格式化
          if (this.dataMap.birthday === null) {
            this.dataMap.birthday = "";
          } else {
            this.dataMap.birthday =
              this.dataMap.birthday.substr(0, 4) +
              "-" +
              this.dataMap.birthday.substr(4, 2) +
              "-" +
              this.dataMap.birthday.substr(6, 2);
          }
          // 最后登录时间格式化
          if (this.dataMap.lastTime === null) {
            this.dataMap.lastTime = "";
          } else {
            this.dataMap.lastTime =
              this.dataMap.lastTime.substr(0, 4) +
              "-" +
              this.dataMap.lastTime.substr(4, 2) +
              "-" +
              this.dataMap.lastTime.substr(6, 2) +
              " " +
              this.dataMap.lastTime.substr(8, 2) +
              ":" +
              this.dataMap.lastTime.substr(10, 2);
          }
        } else {
          this.$message({ message: resp.message, type: "warning" });
        }
      });
    },
    // 打开编辑窗口
    handleEdit() {
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        // 异步事件
        this.$refs["pojoForm"].resetFields();
      });
      var token = store.state.user.token;
      getInfo(token).then((response) => {
        const resp = response;
        if (resp.flag) {
          this.pojo = resp.data;
          // 生日格式化
          this.pojo.birthday = Moment(this.pojo.birthday, "YYYYMMDD").format(
            "YYYY-MM-DD"
          );
        } else {
          this.$message({ message: resp.message, type: "warning" });
        }
      });
    },
    // 提交更新数据
    updateData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 生日格式化
          this.pojo.birthday = Moment(this.pojo.birthday, "YYYYMMDD").format(
            "YYYYMMDDHHmmss"
          );
          update(this.pojo).then((response) => {
            const resp = response;
            if (resp.flag) {
              // 更新成功, 刷新列表数据
              this.fetchData();
              this.dialogFormVisible = false; //关闭窗口
              this.$message({ message: resp.message, type: "success" });
            } else {
              this.$message({ message: resp.message, type: "warning" });
              // 更新失败
            }
          });
        } else {
          return false;
        }
      });
    },
    // 打开密码修改框
    handlePwd() {
      this.dialogFormPwdVisible = true;
      this.$nextTick(() => {
        this.$refs["ruleForm"].resetFields();
      });
    },
    // 提交密码修改
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updatePwd(store.state.user.userKey, this.ruleForm.checkPass).then(
            (response) => {
              const resp = response;
              this.$message({
                message: resp.message,
                type: resp.flag ? "success" : "warning",
              });

              if (resp.flag) {
                // 修改成功, 清除本地数据, 重新登录
                this.handleLogout();
                // 关闭窗口
                this.dialogFormPwdVisible = false;
              }
            }
          );
        } else {
          return false;
        }
      });
    },
    // 退出，重新登录
    async handleLogout() {
      await this.$store.dispatch("user/logout");
      this.$router.push(`/login?redirect=${this.$route.fullPath}`);
      this.$router.replace({ path: "/login" });
      location.reload();
    },
  },
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
}

.dialog-footer {
  padding: 10px 10px 10px 10px;
  text-align: center;
}

#textArea {
  border: none;
  font-size: 12px;
  font-weight: bold;
}

.el-form {
  padding: 10px;
}

.el-dialog__body {
  padding: 10px 10px 10px 10px;
}

.el-dialog__footer {
  padding: 10px 10px 10px 10px;
  text-align: center;
}
</style>
